package mysql

import (
	"project/pkg/models"
	"strconv"
)

func (m Mysql) StudentCheckExist(studentId string) (exist bool, info *models.StudentInfo, err error) {
	var count int64
	exist = false
	err = m.db.Table("student_info").Where("student_id = ?", studentId).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		exist = true
		err = m.db.Table("student_info").Where("student_id = ?", studentId).First(&info).Error
		if err != nil {
			return
		}
	}
	return

}
func (m Mysql) StudentCheckExistByOpenID(openid string) (exist bool, info *models.StudentInfo, err error) {
	var count int64
	exist = false
	err = m.db.Table("student_info").Where("wx_open_id = ?", openid).Count(&count).Error
	if err != nil {
		return
	}
	if count > 0 {
		exist = true
		err = m.db.Table("student_info").Where("wx_open_id = ?", openid).First(&info).Error
		if err != nil {
			return
		}
	}
	return

}
func (m Mysql) StudentUpdateInfoBuID(student *models.StudentInfo) (err error) {
	return m.db.Table("student_info").Save(&student).Error
}
func (m Mysql) StudentDeleteByID(studentId string) (err error) {
	return m.db.Table("student_info").Unscoped().Where("id = ?", studentId).Delete(&models.StudentInfo{}).Error
}
func (m Mysql) StudentQueryClass(classId string, page, size int) (res []*models.StudentInfo, count int64, err error) {
	err = m.db.Table("student_info").Where("class_id = ?", classId).Offset((page - 1) * size).Limit(size).Count(&count).Find(&res).Error
	return
}
func (m Mysql) StudentQueryStudentID(studentId string) (res *models.StudentInfo, err error) {
	err = m.db.Table("student_info").Where("student_id = ?", studentId).First(&res).Error
	return
}
func (m Mysql) StudentQueryOpenId(val string) (res *models.StudentInfo, err error) {
	err = m.db.Table("student_info").Where("wx_open_id = ?", val).First(&res).Error
	return
}

func (m Mysql) StudentUpdateClassInfo(classId string) (people, leave, nowPeople string, err error) {
	var (
		pCount, lCount, nowCount int64
	)
	err = m.db.Table("student_info").Where("class_id = ?", classId).Count(&pCount).Error
	err = m.db.Table("student_info").Where("class_id = ? and leave_status = 1", classId).Count(&lCount).Error
	err = m.db.Table("student_info").Where("class_id = ? and leave_status = 0", classId).Count(&nowCount).Error
	people = strconv.FormatInt(pCount, 10)
	leave = strconv.FormatInt(lCount, 10)
	nowPeople = strconv.FormatInt(nowCount, 10)
	return
}
